<?php
namespace Kuoqi\DbDriver\Sql;

class Join{

    public $list = array();

    public function input($rex,$cdtion){
        //智能识别字符串内容，并判定
        $join = new JoinPart();
        $join->input($rex,$cdtion);
        $this->list[] = $join;
        return $join;
    }

    public function output(){
        $stream = '';
        foreach ($this->list as $item){
            if($stream){
                $stream .= ' '.$item->output();
            }else{
                $stream = $item->output();
            }
        }
        return $stream;
    }

}
class JoinPart{

	public $rex = 'INNER';//join关系的部分
	public $table = '';//table部分
	public $cdtion = '';//condition部分
	
	public function input($rex,$cdtion){
		//智能识别字符串内容，并判定
		$table = '';
		$alias = '';
		$code = '';
		if(!$cdtion){
			//这种情况，为condition作为【判定条件
			//需要将rex中的condition剥离出来
			$oncode = stripos($rex,'on');
			if($oncode===false){
				throw new \Kuoqi\Error('请检查【'.$rex.'】的 关联条件是否出错');
			}
			$cdtion = trim(substr($rex,$oncode + 2,strlen($rex)));
			$rex = trim(substr($rex,0,$oncode));
		}
		
		//剥离table的部分
		$tbcode = stripos($rex,'join');
		if($tbcode===false){
			$table = $rex;
		}else{
			$alias = '';
			$table = substr($rex,$tbcode + 5,strlen($rex));
			if($table){
				//判定是否有别名，如果有别名，则需要处理别名部分
				$lcode = stripos($rex,'as');	
				if($lcode!==false){
					$alias = trim(substr($table,$lcode+2,strlen($table)));
					$table = trim(substr($table,0,$lcode));
				}
			}
			//这种情况join部分为
			$join = substr($rex,0,$tbcode);
			$this->rex = strtoupper(trim($join));
		}
		$this->table = new Table($table,$alias);
		$this->cdtion = $cdtion;
		
	}
	
	public function output(){
		return sprintf('%s JOIN %s ON %s',
			$this->rex,
			$this->table->output(),
			$this->cdtion
		);	
	}
	
}